package com.longrise.android.byjk.plugins.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.CloseModeConstants;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.tabfirst.HomeFragment;
import com.longrise.android.byjk.plugins.tabsecond.SecondFragment;
import com.longrise.android.byjk.plugins.tabthird.MineFragment;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.base.BaseActivity2;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.ActivityUtil;
import com.longrise.common.utils.FolderConstants;
import com.longrise.common.utils.PrintLog;
import com.longrise.filedownloader.DownloadService;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * Created by callxkj on 2017/10/22.
 * 项目主activity
 */

public class MainActivity extends BaseActivity2 implements TabLayout.OnTabSelectedListener {

    //Tab 文字
    private final int[] mTab_titles = new int[]{R.string.first_tab, R.string.second_tab, R.string.third_tab};
    //Tab 图片
    private final int[] mTab_images = new int[]{R.drawable.selector_tab_first,
            R.drawable.selector_tab_second, R.drawable.selector_tab_third};

    private TabLayout mTb;
    private static final String ISFIRST = "isfirst";
    private long mExitTime;
    private FrameLayout mFl;
    private Bundle mBundle;
    private HomeFragment mHomeFragment;
    private SecondFragment mSecondFragment;
    private MineFragment mMineFragment;
    private FragmentManager mSupportFragmentManager;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        getWindow().setBackgroundDrawable(null);
        mBundle = savedInstanceState;
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        mFl = (FrameLayout) findViewById(R.id.main_container);
        mTb = (TabLayout) findViewById(R.id.main_tablayout);
        setToolbarVisible(false);
        initFragment();
        setTabs();
        initAdapter();
        initSettings();
    }

    @Override
    public void onToolbarBackClick() {

    }

    /**
     * 初始化fragment
     */
    private void initFragment() {
        mSupportFragmentManager = getSupportFragmentManager();
        if (mBundle != null) {
            mHomeFragment = (HomeFragment) mSupportFragmentManager.findFragmentByTag(HomeFragment.class.getName());
            mSecondFragment = (SecondFragment) mSupportFragmentManager.findFragmentByTag(SecondFragment.class.getName());
            mMineFragment = (MineFragment) mSupportFragmentManager.findFragmentByTag(MineFragment.class.getName());
            mSupportFragmentManager.beginTransaction()
                    .show(mHomeFragment)
                    .hide(mSecondFragment)
                    .hide(mMineFragment)
                    .commitAllowingStateLoss();
            MobclickAgent.onPageStart("首页tab");
        } else {
            mHomeFragment = new HomeFragment();
            mSecondFragment = new SecondFragment();
            mMineFragment = new MineFragment();
            mSupportFragmentManager.beginTransaction()
                    .add(R.id.main_container, mHomeFragment, HomeFragment.class.getName())
                    .add(R.id.main_container, mSecondFragment, SecondFragment.class.getName())
                    .add(R.id.main_container, mMineFragment, MineFragment.class.getName())
                    .hide(mSecondFragment)
                    .hide(mMineFragment)
                    .commitAllowingStateLoss();
            MobclickAgent.onPageStart("首页tab");
        }
    }

    private void setTabs() {
        for (int i = 0; i < mTab_images.length; i++) {
            TabLayout.Tab tab = mTb.newTab();
            View tabview = View.inflate(this, R.layout.tab_main, null);
            tab.setCustomView(tabview);

            TextView tvTab = (TextView) tabview.findViewById(R.id.tv_tab);
            tvTab.setText(mTab_titles[i]);
            ImageView ivTab = (ImageView) tabview.findViewById(R.id.img_tab);
            ivTab.setImageResource(mTab_images[i]);
            mTb.addTab(tab);
        }
    }

    private void initAdapter() {

        mTb.addOnTabSelectedListener(this);
    }


    private void initSettings() {
        try {
            ActivityUtil.removeActivity(this);
            ActivityUtil.finishAllAcivity();
            ActivityUtil.addActivity(this);

            // 检查版本号
            // checkVersion();
            // 将app的图片存储到sd卡
            initAppImage();
            // 初始化app的一些基本设置
            CloseModeConstants.setWillToLogin(false);
            if (TextUtils.isEmpty(Control.getDeifinition())) {
                Control.setDeifinition("1");
            }
            if (TextUtils.isEmpty(Control.getCacheMaxSize())) {
                Control.setCacheMaxSize("1024");
            }
            // 如果删应用升级后 本地以前有缓存的视频应该删除 防止断点续传出问题
            toClearCache();
            // 初始化downloadmanage
            initDownloadService();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 将app图片存入sd卡 为了分享使用
     */
    private void initAppImage() {
        InputStream is = null;
        FileOutputStream fs = null;

        try {
            File file = new File(FolderConstants.ICON_DIR + "/logoshare.jpg");
            if (file.exists()) {
                // 如果app的icon存在则返回
                return;
            }
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                boolean mkdirs = parentFile.mkdirs();
            }
            // boolean sdCardFile = file.createNewFile();
            int byteread = 0;
            byte[] buffer = new byte[1024 * 4];
            is = getResources().getAssets().open("logoshare.png");
            fs = new FileOutputStream(file);
            while ((byteread = is.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != fs) {
                    fs.close();
                }
            } catch (Exception e2) {

            }
        }
    }


    /**
     * 如果删应 升级后 本地以前有缓存 视频应该删除 防止断 续传出问题
     */
    private void toClearCache() {
        boolean isfirst = CacheUtils.getBoolean(ISFIRST);
        if (!isfirst) {
            FileUtil.deleteFolder(FolderConstants.VIDEO_DIR);
            CacheUtils.setBoolean(ISFIRST, true);
        }
    }

    /**
     * 初始化下载的service
     */
    private void initDownloadService() {
        DownloadService.setUserid(UserInfor.getInstance().getUserid());
        this.startService(new Intent(this, DownloadService.class));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                showToast(getString(R.string.exit_tips));
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //--------------- 底部tab的选择事件 -----------------------
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int position = tab.getPosition();
        switch (position) {
            case 0:
                mSupportFragmentManager.beginTransaction()
                        .show(mHomeFragment)
                        .hide(mSecondFragment)
                        .hide(mMineFragment)
                        .commitAllowingStateLoss();
                mHomeFragment.show(true);
                MobclickAgent.onPageStart("首页tab");
                break;
            case 1:
                mSupportFragmentManager.beginTransaction()
                        .show(mSecondFragment)
                        .hide(mHomeFragment)
                        .hide(mMineFragment)
                        .commitAllowingStateLoss();
                mHomeFragment.show(false);
                MobclickAgent.onPageStart("保险医学tab");
                break;
            case 2:
                mSupportFragmentManager.beginTransaction()
                        .show(mMineFragment)
                        .hide(mSecondFragment)
                        .hide(mHomeFragment)
                        .commitAllowingStateLoss();
                mHomeFragment.show(false);
                MobclickAgent.onPageStart("我的tab");
                break;
        }


    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        switch (tab.getPosition()) {
            case 0:
                MobclickAgent.onPageEnd("首页tab");
                break;
            case 1:
                MobclickAgent.onPageEnd("保险医学tab");
                break;
            case 2:
                MobclickAgent.onPageEnd("我的tab");
                break;
            default:
                break;
        }
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
    //--------------------------------------------------------


    @Override
    public boolean isFragmentActivity() {
        return true;
    }
}
